{% extends "base.html" %}
{% load static %}
{% load gravatar %}
{% load databasefilters %}



{% block title %}RMG: Molecule Search{% endblock %}

{% block extrahead %}
<!-- ChemDoodle Setup -->
<link href="{% static 'css/ChemDoodleWeb.css' %}" rel="stylesheet" type="text/css"/>
<script src="{% static 'js/ChemDoodleWeb.js' %}" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha256-KM512VNnjElC30ehFwehXjx1YCHPiQkOPmqnrWtpccM=" crossorigin="anonymous"></script>
<link href="{% static 'css/jquery-ui-1.11.4.css' %}" rel="stylesheet" type="text/css"/>
<script src="{% static 'js/ChemDoodleWeb-uis.js' %}" type="text/javascript"></script>

<script type="text/javascript">
// the function used to resolve the identifier into an adjacency list
function resolve(){
    var spField = $('#id_species');
    var identifier = $('#id_species_identifier').val();
    var url = '/adjacencylist/' + escape(identifier);
    spField.val("Loading...");
    $('.result').hide();
    var jqxhr = $.get(url,function(structure) {
                     spField.val(structure);
                 })
                 .fail(function(obj, status, error) {
                     spField.val(error+'\n'+obj.responseText.split('\n')[0]);
                 });
};

// prevent "enter" keypress in the identifier field from submitting the form,
// but instead make it resolve the identifier and select the submit button.
$(document).ready(function() {
    $("#id_species_identifier").bind("keypress", function(e) {
        var c = e.which ? e.which : e.keyCode;
        if (c == 13) {
            resolve();
            $("input:submit:first").focus();
            return false;
        }
    });

{% if smiles %}
// Update list of names
    var url = '/cactus/{{ smiles|urlencode:"" }}/names';
    var jqxhr = $.get(url,function(names) {
                     $('#species_names').html(names);
                 })
                 .fail(function(obj, status, error) {
                     $('#species_names').html(error+'\n'+obj.responseText.split('\n')[0]);
                 });
{% endif %}

});
// end of document.ready

// Functions to show and hide molecule editor
var show = function(id) {
    document.getElementById(id).style.display ='block';
}
var hide = function(id) {
    document.getElementById(id).style.display ='none';
}

// Function to get SMILES from molecule editor and fetch adjlist
function submitMolecule() {
    var mol = sketcher.getMolecule();
    var dummy = new ChemDoodle.io.JSONInterpreter().molTo(mol);

    var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    $.ajax({
        url: '/database/ajax_adjlist_request/',
        method: 'post',
        data: {'data': JSON.stringify(dummy)},
        dataType: 'text',
        success: function (data) {
            $('#id_species').val(data);
        }
    });
}

</script>

<style type="text/css">

.overlay {
    display: none;
    position: fixed;
    padding: 9px;
    width: 600px;
    left: 50%;
    margin-left: -310px;
    height: 520px;
    top: 50%;
    margin-top:-270px;
    text-align:center;
    overflow: auto;
    background-color: #efefef;
    border: 1px solid #e3e3e3;
    border-radius: 4px;
    box-shadow: 0 0 10px rgba(0,0,0,0.3);
    z-index:20;
}

#applet {
    padding: 7px
}

</style>

{% endblock %}

{% block navbar_items %}
<li><a href="{% url 'molecule-search' %}">Molecule Search</a></li>
{% endblock %}

{% block page_title %}Molecule Search{% endblock %}

{% block page_body %}

<p>
Use this form to find a species from its adjacency list.
You can quickly fill in the adjacency list part of the form by entering any species identifier,
such as a 
<a href="javascript:$('#id_species_identifier').val('CCC=CC(=O)O');resolve();">SMILES</a>,
<a href="javascript:$('#id_species_identifier').val('InChI=1S/C7H8O/c8-6-7-4-2-1-3-5-7/h1-5,8H,6H2');resolve();">InChI</a>,
<a href="javascript:$('#id_species_identifier').val('623-42-7');resolve();">CAS number</a>, or 
<a href="javascript:$('#id_species_identifier').val('2,3 dimethyl hexan-4-ol');resolve();">species name</a>
 in the 'species identifier' field and pressing tab.
This is translated into an adjacency list using the <a href="http://cactus.nci.nih.gov/chemical/structure">NCI Chemical Identifier Resolver</a>.
Do not submit the form until the adjacency list has loaded.
</p>

<p>
You may use the "Structure Input" function to draw a molecular structure which will be converted to an adjacency list.
Please note that this functionality is currently in beta, so there may be structures which cannot be correctly
converted to an adjacency list. In particular, lone pairs must be drawn explicitly for the time being.
</p>

<p>
Currently, we only support searches for electrically neutral species containing H, He, C, N, O, F, Ne, Si, S, Cl, Ar, Br, I, and surface site (X).
Species like ions and salts are not supported.
</p>

<div class="overlay" id="editor">
  <div id="applet">
      <script>
      var sketcher = new ChemDoodle.SketcherCanvas('sketcher', 500, 400, {useServices:false, oneMolecule:true});
      </script>
  </div>

  <button type="button" onclick="hide('editor');submitMolecule();">Submit</button>
  <button type="button" onclick="hide('editor');">Cancel</button>
</div>

<button type="button" onclick="show('editor');">Structure Input</button>

<form method="post" id="species_form">
<table>
   
{{ form.as_table }}
<tr>
   <th>{% csrf_token %}</th>
   <td>
      <input type="submit" value="Draw Molecule" name="draw" />
      <input type="submit" value="Search Thermochemistry" name="thermo" />
      <input type="submit" value="Search Transport Properties" name="transport" /><br>
      <input type="submit" value="Generate Resonance Structures" name="resonance" />
      <input type="submit" value="Reset Form" name="reset" />
   </td>
</tr>
</table>
</form>

{% if structure_markup %}
<table>
<tr class="result">
<th>Molecule Structure:</th>
<td style="padding: 40px;">{{ structure_markup|safe }}</td>
</tr>
<tr class ="result">
    <th>Molecular Formula:</th>
    <td>{{ molecule.get_formula|renderMF }}</td>
</tr>
<tr class ="result">
    <th>Molecular Weight:</th>
    <td>{{ molecule.get_molecular_weight|renderMW }}</td>
</tr>
<tr class="result">
<th>InChI:</th>
    {% if inchi %}
        <td>{{ inchi }}</td>
    {% else %}
        <td>Unable to generate InChI</td>
    {% endif %}
</tr>
<tr class="result">
<th>SMILES:</th>
    {% if smiles %}
        <td>{{ smiles }}</td>
    {% else %}
        <td>Unable to generate SMILES</td>
    {% endif %}
</tr>
<tr class="result">
<th valign="top">Adjacency List:</th>
<td>{{ molecule.to_adjacency_list|renderAdjlist }}</td>
</tr>
<tr class="result">
<th valign="top">Old Adjacency List:</th>
<td>{{ oldAdjlist|renderAdjlist }}</td>
</tr>
<tr class="result" style="white-space: pre-wrap;">
<th style="vertical-align: top;">Names:</th>
<td id="species_names"></td>
</tr>
</table>
{% endif %}

{% endblock %}
